package com.org.matomo.demo.slice;

import com.org.matomo.demo.MyApplication;
import com.org.matomo.demo.PixelMapUtil;
import com.org.matomo.demo.ResourceTable;
import com.org.matomo.demo.button.RTextView;
import com.org.matomo.demo.util.StrUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.render.opengl.Utils;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import org.matomo.sdk.dispatcher.Packet;
import org.matomo.sdk.extra.MatomoApplication;
import org.matomo.sdk.extra.TrackHelper;

import java.util.ArrayList;
import java.util.Collections;

public class SettingAbliltySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_settings);
        refreshUI();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void refreshUI() {
        RTextView button = (RTextView) findComponentById(ResourceTable.Id_bindtoapp);
        button.setClickedListener(component -> {
            MyApplication matomoApplication = (MyApplication) getAbility().getAbilityPackage();
            TrackHelper.track().screens(matomoApplication).with(matomoApplication.getTracker());
        });

        Checkbox dryRunCheckbox = (Checkbox) findComponentById(ResourceTable.Id_dryRunCheckbox);
        Checkbox optOutCheckbox = (Checkbox) findComponentById(ResourceTable.Id_optOutCheckbox);
        PixelMapUtil.checkBoxAddStatus(ResourceTable.Media_check_yes, ResourceTable.Media_check_no, this, dryRunCheckbox);
        PixelMapUtil.checkBoxAddStatus(ResourceTable.Media_check_yes, ResourceTable.Media_check_no, this, optOutCheckbox);

        dryRunCheckbox.setCheckedStateChangedListener((absButton, b) -> {
            MyApplication matomoApplication = (MyApplication) getAbility().getAbilityPackage();
            matomoApplication.getTracker().setDryRunTarget(b ? Collections.synchronizedList(new ArrayList<Packet>()) : null);
        });
        optOutCheckbox.setCheckedStateChangedListener((absButton, b) -> {
            MyApplication matomoApplication = (MyApplication) getAbility().getAbilityPackage();
            matomoApplication.getTracker().setOptOut(b);
        });

        TextField textDispatchIntervallInput = (TextField) findComponentById(ResourceTable.Id_dispatchIntervallInput);
        TextField textSessionTimeoutInput = (TextField) findComponentById(ResourceTable.Id_sessionTimeoutInput);
        textDispatchIntervallInput.setText(Long.toString(
                ((MatomoApplication) getAbility().getAbilityPackage()).getTracker().getDispatchInterval()));
        textSessionTimeoutInput.setText(Long.toString(
                ((MatomoApplication) getAbility().getAbilityPackage()).getTracker().getSessionTimeout() / 60000));
        textDispatchIntervallInput.addTextObserver((s, i, i1, i2) -> {
            System.out.println("xcccccc>>>>" + "textDispatchIntervallInput");
            if (s != null && s.length() > 0 && !StrUtil.isNumeric(s)) {
                textDispatchIntervallInput.setText(s.substring(0, s.length() - 1));
                setDispatchInterval(s.substring(0, s.length() - 1));
            }

            if (s != null && s.length() > 0 && StrUtil.isNumeric(s)) {
                setDispatchInterval(s);
            }
        });

        textSessionTimeoutInput.addTextObserver((s, i, i1, i2) -> {
            if (s != null && (s.length() == 0 || s.length() > 9)) {
                eventHandler.sendEvent(0, 100);
            }
            if (s != null && s.length() > 0 && !StrUtil.isNumeric(s)) {
                textSessionTimeoutInput.setText(s.substring(0, s.length() - 1));
                setSessionTimeout(s.substring(0, s.length() - 1));
            }
            if (s != null && s.length() > 0 && StrUtil.isNumeric(s)) {
                setSessionTimeout(s);
            }
        });
    }

    private void setDispatchInterval(String s) {
        try {
            int interval = Integer.parseInt(s.trim());
            ((MyApplication) getAbility().getAbilityPackage()).getTracker()
                    .setDispatchInterval(interval);
        } catch (NumberFormatException e) {
            System.out.println("xcccccc>>>>" + "textDispatchIntervallInput");
        }
    }

    private void setSessionTimeout(String s) {
        try {
            int timeoutMin = Integer.parseInt(s.trim());
            timeoutMin = Math.abs(timeoutMin);
            ((MyApplication) getAbility().getAbilityPackage()).getTracker()
                    .setSessionTimeout(timeoutMin * 60);
        } catch (NumberFormatException e) {
            System.out.println("xcccccc>>>>" + "setSessionTimeout");
        }
    }

    private final EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        /**
         * This is the code that will increment the progress variable and so
         * spin the wheel
         *
         * @param msg msg
         */
        @Override
        public void processEvent(InnerEvent msg) {
            int id = msg.eventId;
            if (id == 0) {
                ((TextField) findComponentById(ResourceTable.Id_sessionTimeoutInput)).setText("30");
            }
            super.processEvent(msg);
        }
    };
}
